/**
 * 权限校验
 * Vue Router中，前置钩子函数 beforeEach(to,from,next)
 * to: 即将要进入的目标路由对象
 * from：即将要离开的路由对象
 * next：是一个方法，可以指定路由地址，进行路由跳转
 */
import NProgress from 'nprogress'
import router from "./router";
import store from './store'
import {initMenu} from './util/menuToRoute'
const ignoreUrl = ['/test']
router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = store.getters.getToken;
  if(ignoreUrl.includes(to.path)){
    next();
  }else if (to.path === "/login") {
    next();
  } else {
    if (!token) {
      next(`/login?redirect=${to.path}`);
    } else {
      const userInfo = store.getters.getUserInfo;
      if (userInfo) {
        initMenu(router,store)
        next();
      } else {
        store.dispatch('addUser',token).then(flage => {
          if (flage) {
            initMenu(router,store)
            next();
          } else {
            next(`/login?redirect=${to.path}`);
          }
        });
      }
    }
  }
});
router.afterEach(()=>{
  NProgress.done()
})